/*
 * Copyright (c) 2021
 * User:mallplus多商户商城
 * File:MallplusJob.java
 * Date:2021/01/12 19:29:12
 */

package com.qyine.rlmall.jobhandler;


import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qyine.rlmall.enums.AllEnum;
import com.qyine.rlmall.enums.ConstansValue;
import com.qyine.rlmall.enums.OrderStatus;
import com.qyine.rlmall.fenxiao.entity.FenxiaoMemberTotal;
import com.qyine.rlmall.fenxiao.entity.FenxiaoRecords;
import com.qyine.rlmall.fenxiao.mapper.FenxiaoMemberTotalMapper;
import com.qyine.rlmall.fenxiao.mapper.FenxiaoRecordsMapper;
import com.qyine.rlmall.service.impl.IOmsOrderService;
import com.qyine.rlmall.service.impl.RedisUtil;
import com.qyine.rlmall.sms.entity.*;
import com.qyine.rlmall.sms.mapper.*;
import com.qyine.rlmall.sys.entity.AdminDayStatics;
import com.qyine.rlmall.sys.entity.SysStore;
import com.qyine.rlmall.sys.entity.SysStoreDepositLog;
import com.qyine.rlmall.sys.entity.SysStoreSettleRecords;
import com.qyine.rlmall.sys.mapper.AdminDayStaticsMapper;
import com.qyine.rlmall.sys.mapper.SysStoreDepositLogMapper;
import com.qyine.rlmall.sys.mapper.SysStoreMapper;
import com.qyine.rlmall.sys.mapper.SysStoreSettleRecordsMapper;
import com.qyine.rlmall.ums.entity.UmsMember;
import com.qyine.rlmall.ums.mapper.UmsMemberMapper;
import com.qyine.rlmall.utils.CommonResult;
import com.qyine.rlmall.utils.DateUtils;
import com.qyine.rlmall.vo.Rediskey;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.qyine.rlmall.cms.entity.CmsSubject;
import com.qyine.rlmall.cms.mapper.CmsSubjectMapper;

import com.qyine.rlmall.oms.entity.OmsOrder;
import com.qyine.rlmall.oms.entity.OmsOrderReturnApply;
import com.qyine.rlmall.oms.mapper.OmsOrderMapper;
import com.qyine.rlmall.oms.mapper.OmsOrderReturnApplyMapper;

import com.qyine.rlmall.pms.entity.PmsProduct;
import com.qyine.rlmall.pms.mapper.PmsProductMapper;
import com.qyine.rlmall.sms.entity.*;
import com.qyine.rlmall.sms.mapper.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * https://github.com/shenzhuan/mallplus on 2018/8/24.
 * 订单超时取消并解锁库存的定时器
 * 1）0 0 2 1 * ? *   表示在每月的1日的凌晨2点调整任务
 *
 * 　　（2）0 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业
 *
 * 　　（3）0 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作
 *
 * 　　（4）0 0 10,14,16 * * ?   每天上午10点，下午2点，4点
 *
 * 　　（5）0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时
 *
 * 　　（6）0 0 12 ? * WED    表示每个星期三中午12点
 *
 * 　　（7）0 0 12 * * ?   每天中午12点触发
 *
 * 　　（8）0 15 10 ? * *    每天上午10:15触发
 *
 * 　　（9）0 15 10 * * ?     每天上午10:15触发
 *
 * 　　（10）0 15 10 * * ? *    每天上午10:15触发
 *
 * 　　（11）0 15 10 * * ? 2005    2005年的每天上午10:15触发
 *
 * 　　（12）0 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发
 *
 * 　　（13）0 0/5 14 * * ?    在每天下午2点到下午2:55期间的每5分钟触发
 *
 * 　　（14）0 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
 *
 * 　　（15）0 0-5 14 * * ?    在每天下午2点到下午2:05期间的每1分钟触发
 *
 * 　　（16）0 10,44 14 ? 3 WED    每年三月的星期三的下午2:10和2:44触发
 *
 * 　　（17）0 15 10 ? * MON-FRI    周一至周五的上午10:15触发
 *
 * 　　（18）0 15 10 15 * ?    每月15日上午10:15触发
 *
 * 　　（19）0 15 10 L * ?    每月最后一日的上午10:15触发
 *
 * 　　（20）0 15 10 ? * 6L    每月的最后一个星期五上午10:15触发
 *
 * 　　（21）0 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发
 *
 * 　　（22）0 15 10 ? * 6#3   每月的第三个星期五上午10:15触发
 */

@Component
public class MallplusJob {
    private Logger log = LoggerFactory.getLogger(MallplusJob.class);
    @Autowired
    private IOmsOrderService portalOrderService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private PmsProductMapper productMapper;
    @Resource
    private CmsSubjectMapper subjectService;
    @Resource
    private OmsOrderMapper orderMapper;
    @Resource
    private UmsMemberMapper IUmsMemberService;
    @Resource
    private FenxiaoRecordsMapper fenxiaoRecordsMapper;
    @Resource
    private SysStoreMapper storeMapper;
    @Resource
    private AdminDayStaticsMapper dayStaticsMapper;
    @Resource
    private SysStoreDepositLogMapper sysStoreDepositLogMapper;
    @Resource
    private SmsHomeNewProductMapper homeNewProductService;
    @Resource
    private SmsHomeRecommendProductMapper homeRecommendProductService;
    @Resource
    private SmsHomeBrandMapper homeBrandService;
    @Resource
    private SmsHomeRecommendSubjectMapper homeRecommendSubjectService;
    @Resource
    private OmsOrderReturnApplyMapper orderReturnApplyService;
    @Resource
    private SmsGroupRecordMapper groupRecordMapper;
    @Resource
    private SmsGroupMemberMapper groupMemberMapper;

    @Resource
    private SysStoreSettleRecordsMapper storeSettleRecordsMapper;
    @Resource
    private FenxiaoMemberTotalMapper fenxiaoMemberTotalService;
    @Resource
    private SmsGroupActivityMapper groupActivityService;
    @Resource
    private SmsGroupMapper groupService;
    @Resource
    private SmsCouponHistoryMapper couponHistoryMapper;
    /**
     * 更新用户过期的优惠券状态 半小时计算一次
     */
    @XxlJob("updateMemberCouponStatus")
    public ReturnT<String> updateMemberCouponStatus(String param) {
        log.info("更新用户过期的优惠券状态 半小时计算一次start = {}", new Date());
        List<SmsCouponHistory> couponHistoryList= couponHistoryMapper.selectList(new QueryWrapper<SmsCouponHistory>().eq("use_status",0).lt("end_time",new Date()));
        for (SmsCouponHistory history:couponHistoryList){
            history.setUseStatus(3);
            couponHistoryMapper.updateById(history);
        }
        log.info("更新用户过期的优惠券状态 半小时计算一次end = {}", new Date());
        return ReturnT.SUCCESS;
    }
    /**
     * 拼团成功后 将订单状态改为发货
     * 查询所有拼团成功且未处理的拼团记录
     * 更新订单状态为发货 拼团记录为已处理
     */
   /* @XxlJob("pinTuanOrder")
    public ReturnT<String> pinTuanOrder(String param) {
        log.info("拼团成功后 将订单状态改为发货start = {}", new Date());
      List<SmsGroupRecord> list = groupRecordMapper.selectList(new QueryWrapper<SmsGroupRecord>().eq("status",2).eq("handle_status",1));
       for (SmsGroupRecord groupRecord:list){
           List<SmsGroupMember> groupMembers = groupMemberMapper.selectList(new QueryWrapper<SmsGroupMember>().eq("group_record_id", groupRecord.getId()).eq("status", 2));
          if (groupMembers!=null && groupMembers.size()>0){
              List<Long> ids = groupMembers.stream()
                      .map(SmsGroupMember::getOrderId)
                      .collect(Collectors.toList());
              if (ids.size()>0){
                  OmsOrder order = new OmsOrder();
                  order.setStatus(OrderStatus.TO_DELIVER.getValue());
                  order.setModifyTime(new Date());
                  orderMapper.update(order,new QueryWrapper<OmsOrder>().in("status",ids));
                  groupRecord.setHandleStatus(2);
                  groupRecordMapper.updateById(groupRecord);
              }
          }
       }
        log.info("拼团成功后 将订单状态改为发货end = {}", new Date());
        return ReturnT.SUCCESS;
    }*/
    /**
     * 退款
     */
    @XxlJob("refund")
    public ReturnT<String> refund(String param) {
        log.info("退款 10分支计算一次start = {}", new Date());
        List<Integer> ids = Arrays.asList(1,3);
      List<OmsOrderReturnApply> returnApplyList=  orderReturnApplyService.selectList(new QueryWrapper<OmsOrderReturnApply>().
              eq("status", AllEnum.OmsOrderReturnApplyStatus.REFUNDING.code()).eq("refund_status",1).in("type",ids));
        for (OmsOrderReturnApply orderReturnApply:returnApplyList){
            try {
                portalOrderService.refund(orderReturnApply);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
        log.info("退款 10分支计算一次end = {}", new Date());
        return ReturnT.SUCCESS;
    }
    /**
     * 清理 因为商品被删除 导致的数据关联问题
     */
    @XxlJob("clearGoodsRelate")
    public ReturnT<String> clearGoodsRelate(String param) {
        log.info("清理 因为商品被删除 导致的数据关联问题start = {}", new Date());
        List<SmsHomeRecommendProduct> homeRecommendProductList = homeRecommendProductService.selectList(new QueryWrapper<SmsHomeRecommendProduct>().select("id,product_id"));
        List<SmsHomeNewProduct> homeNewProducts = homeNewProductService.selectList(new QueryWrapper<SmsHomeNewProduct>().select("id,product_id"));
        List<PmsProduct> productList = productMapper.selectList(new QueryWrapper<PmsProduct>().select("id"));
        List<Long> ids = productList.stream().map(PmsProduct::getId).collect(Collectors.toList()) ;
        for (SmsHomeNewProduct product:homeNewProducts){
              if (!ids.contains(product.getProductId())){
                  homeNewProductService.deleteById(product.getId());
              }
        }
        for (SmsHomeRecommendProduct product:homeRecommendProductList){
            if (!ids.contains(product.getProductId())){
                homeRecommendProductService.deleteById(product.getId());
            }
        }
        List<SmsGroupActivity> groupActivityList = groupActivityService.selectList(new QueryWrapper<SmsGroupActivity>().select("id,goods_ids"));
        for (SmsGroupActivity product:groupActivityList){
            String []goodsIds= product.getGoodsIds().split(",");
            for (String id :goodsIds){
                if (!ids.contains(Long.parseLong(id))){
                    groupActivityService.deleteById(product.getId());
                    break;
                }
            }

        }
        List<SmsGroup> groupList = groupService.selectList(new QueryWrapper<SmsGroup>().select("id,goods_id"));
        for (SmsGroup product:groupList){
            if (!ids.contains(product.getGoodsId())){
                groupService.deleteById(product.getId());
            }
        }
        log.info("清理 因为商品被删除 导致的数据关联问题end = {}", new Date());
        return ReturnT.SUCCESS;
    }
    /**
     * cron表达式：Seconds Minutes Hours DayofMonth Month DayofWeek [Year]
     * 每10分钟扫描一次，扫描设定超时时间之前下的订单，如果没支付则取消该订单
     * 正常订单超时时间(分)
     */
    @XxlJob("cancelTimeOutOrder")
    public ReturnT<String> cancelTimeOutOrder(String param) {
        log.info("取消订单，并根据sku编号释放锁定库存start = {}", new Date());
        CommonResult result = portalOrderService.cancelTimeOutOrder();
        log.info("取消订单，并根据sku编号释放锁定库存end:{}", result);
        return ReturnT.SUCCESS;
    }

    /**
     * 自动收货
     * 发货后自动确认收货时间（天）
     */
    @XxlJob("autoDeliveryOrder")
    public ReturnT<String> autoDeliveryOrder(String param) {
        log.info("自动收货start = {}", new Date());
        CommonResult result = portalOrderService.autoDeliveryOrder();
        log.info("自动收货:{}", result);
        return ReturnT.SUCCESS;
    }



    /**
     * 订单完成后自动好评时间（天）
     */
    @XxlJob("autoCommentOrder")
    public ReturnT<String> autoCommentOrder(String param) {
        log.info("订单完成后自动好评时间（天）start = {}", new Date());
        CommonResult result = portalOrderService.autoCommentOrder();
        log.info("订单完成后自动好评时间（天）end:{}", result);
        return ReturnT.SUCCESS;
    }


    /**
     * 佣金计算 计算前一天的订单 凌晨1点
     */
    @Deprecated
   // @XxlJob("memberYongJinCalator")
    public ReturnT<String> memberYongJinCalator(String param) {
        log.info("佣金计算 计算前一天的订单 start....");
        Long t1 = System.currentTimeMillis();
        String yesteday = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -1));
        List<OmsOrder> orders = orderMapper.listByDate(yesteday, 3);
        // 获取订单为 待评价和已完成的
        List<Long> ids = new ArrayList<>();
        for (OmsOrder order : orders) {
            if (order.getStatus() == 4 || order.getStatus() == 5) {
                ids.add(order.getId());
            }
        }
        // 将条件合适的订单的 佣金记录更改状态
        if (ids != null && ids.size() > 0) {
            FenxiaoRecords records = new FenxiaoRecords();
            records.setStatus("2");
            fenxiaoRecordsMapper.update(records, new QueryWrapper<FenxiaoRecords>().in("order_id", ids));
        }
        // 分组佣金记录 更改用户的余额或积分
        List<FenxiaoRecords> fenxiaoRecordss = fenxiaoRecordsMapper.listRecordsGroupByMemberId();
        for (FenxiaoRecords fenxiaoRecords : fenxiaoRecordss) {
            FenxiaoMemberTotal memberTotal= fenxiaoMemberTotalService.selectById(fenxiaoRecords.getMemberId());

            if (memberTotal != null) {
                memberTotal.setCurrentAmout(fenxiaoRecords.getMoney().add(memberTotal.getCurrentAmout()));
                memberTotal.setTotalAmount(fenxiaoRecords.getMoney().add(memberTotal.getTotalAmount()));
                memberTotal.setUpdateTime(new Date());
                fenxiaoMemberTotalService.updateById(memberTotal);
               /* if (fenxiaoRecords.getType() == 1) { // 余额
                    member.setBlance(member.getBlance().add(fenxiaoRecords.getMoney()));
                } else {
                    member.setIntegration(member.getIntegration() + fenxiaoRecords.getMoney().intValue());
                }
                IUmsMemberService.updateById(member);*/
            }else {
                UmsMember member = IUmsMemberService.selectById(fenxiaoRecords.getMemberId());
                memberTotal = new FenxiaoMemberTotal();
                memberTotal.setName(member.getNickname());
                memberTotal.setCurrentAmout(fenxiaoRecords.getMoney());
                memberTotal.setTotalAmount(fenxiaoRecords.getMoney());
                memberTotal.setFrezzAmount(BigDecimal.ZERO);
                memberTotal.setId(fenxiaoRecords.getMemberId());
                memberTotal.setUpdateTime(new Date());
                fenxiaoMemberTotalService.insert(memberTotal);
            }

        }
        log.info("佣金计算 计算前一天的订单end..,耗时" + (System.currentTimeMillis() - t1) / 1000 + "秒");
        return ReturnT.SUCCESS;
    }

    /**
     * 文章浏览量
     */
    @XxlJob("syncArticleView")
    public ReturnT<String> syncArticleView(String param) {
        log.info("开始保存点赞数 、浏览数SyncNodesAndShips");
        try {
            //先获取这段时间的浏览数
            Map<Object, Object> viewCountItem = redisUtil.hGetAll(Rediskey.ARTICLE_VIEWCOUNT_KEY);
            //然后删除redis里这段时间的浏览数
            redisUtil.delete(Rediskey.ARTICLE_VIEWCOUNT_KEY);
            if (!viewCountItem.isEmpty()) {
                for (Object item : viewCountItem.keySet()) {
                    String articleKey = item.toString();
                    String[] kv = articleKey.split("_");
                    Long articleId = Long.parseLong(kv[1]);
                    Integer viewCount = Integer.parseInt(viewCountItem.get(articleKey).toString());
                    CmsSubject subject = subjectService.selectById(articleId);
                    if (subject != null) {
                        CmsSubject cms = new CmsSubject();
                        cms.setId(articleId);
                        cms.setReadCount(subject.getReadCount() + viewCount);
                        log.info("SyncNodesAndShips" + articleId + "," + viewCount);
                        //更新到数据库
                        subjectService.updateById(cms);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        log.info("结束保存点赞数 、浏览数");
        return ReturnT.SUCCESS;
    }

    /**
     * 商品浏览量
     */
    @XxlJob("syncGoodsView")
    public ReturnT<String> syncGoodsView(String param) {
        log.info("开始保存点赞数 、浏览数SyncGoodsView");
        try {
            //先获取这段时间的浏览数
            Map<Object, Object> viewCountItem = redisUtil.hGetAll(Rediskey.GOODS_VIEWCOUNT_KEY);
            //然后删除redis里这段时间的浏览数
            redisUtil.delete(Rediskey.GOODS_VIEWCOUNT_KEY);
            if (!viewCountItem.isEmpty()) {
                for (Object item : viewCountItem.keySet()) {
                    String articleKey = item.toString();//viewcount_1
                    String[] kv = articleKey.split("_");
                    Long articleId = Long.parseLong(kv[1]);
                    Integer viewCount = Integer.parseInt(viewCountItem.get(articleKey).toString());
                    PmsProduct subject = productMapper.selectById(articleId);
                    if (subject != null) {
                        PmsProduct p = new PmsProduct();
                        p.setId(articleId);
                        p.setHit(subject.getHit() + viewCount);
                        log.info("SyncGoodsView" + articleId + "," + viewCount);
                        //更新到数据库
                        productMapper.updateById(p);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        log.info("结束保存点赞数 、浏览数");
        return ReturnT.SUCCESS;
    }

    /**
     * 商户数据日统计 凌晨1点  0 0 1 * * ?
     */
    @XxlJob("storeDayStatics")
    public ReturnT<String> storeDayStatics(String param) throws InterruptedException {

        List<SysStore> storeList = storeMapper.selectList(new QueryWrapper<SysStore>().eq("status", 3));
        log.info("商户数据日统计：{}，共{}个商户需要需要同步", DateUtils.getNowDate(), storeList.size());

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, calendar.getTime());
        calendar.set(Calendar.HOUR_OF_DAY, -24);
        String startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, calendar.getTime());

        //  dayStaticsService.deleteAdminDayStaticsByDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, calendar.getTime()));

        System.out.println(startTime + "," + endTime);
        Thread.sleep(3 * 1000);
        for (SysStore store : storeList) {
            //   List<UmsMember> memberList = IUmsMemberService.list(new QueryWrapper<UmsMember>().eq("store_id",store.getId()));
            List<PmsProduct> productList = productMapper.selectList(new QueryWrapper<PmsProduct>().eq("store_id", store.getId()).between("create_time", startTime, endTime));
            List<OmsOrder> orderList = orderMapper.selectList(new QueryWrapper<OmsOrder>().eq("store_id", store.getId()).between("modify_time", startTime, endTime));

            AdminDayStatics dayStatics = new AdminDayStatics();
            dayStatics.setGoodsCount(productList.size());
            //  dayStatics.setMemberCount(memberList.size());

            Integer payOrderCount = 0;
            BigDecimal payAmount = BigDecimal.ZERO;
            Integer notPayOrderCount = 0;
            BigDecimal notPayAmount = BigDecimal.ZERO;
            for (OmsOrder omsOrder : orderList) {
                if (omsOrder.getPayAmount() != null) {
                    if (omsOrder.getStatus() == OrderStatus.TRADE_SUCCESS.getValue()) {
                        payOrderCount++;
                        payAmount = payAmount.add(omsOrder.getPayAmount());
                    } else {
                        notPayOrderCount++;
                        notPayAmount = notPayAmount.add(omsOrder.getPayAmount());
                    }
                }
            }
            dayStatics.setPayAmount(payAmount);
            dayStatics.setPayOrderCount(payOrderCount);
            dayStatics.setNotPayAmount(notPayAmount);
            dayStatics.setNotPayOrderCount(notPayOrderCount);
            dayStatics.setStoreId(store.getId());
            dayStatics.setStoreName(store.getName());
            dayStatics.setCreateTime(new Date());

            if (dayStatics.getPayOrderCount() > 0 || dayStatics.getNotPayOrderCount() > 0 ||
                    dayStatics.getGoodsCount() > 0) {
                dayStaticsMapper.insert(dayStatics);
            }
            log.info("商户数据日统计end====：{}，商户ID={},商户名称={}", DateUtils.getNowDate(), store.getId(), store.getName());
        }
        log.info("商户数据日统计end====：{}", DateUtils.getNowDate());
        return ReturnT.SUCCESS;
    }

    /**
     * 商户统计 凌晨2点  0 0 2 * * ?
     */
    @XxlJob("storeStatics")
    public ReturnT<String> storeStatics(String param) throws InterruptedException {
        List<AdminDayStatics> dayStatics = dayStaticsMapper.selectAdminDayStaticsGroupBySId();
        log.info("商户统计：{}，共{}个商户需要需要同步", DateUtils.getNowDate(), dayStatics.size());
        for (AdminDayStatics dayStatics1 : dayStatics) {
            SysStore store = new SysStore();
            store.setMemberCount(dayStatics1.getMemberCount());
            store.setId(dayStatics1.getStoreId());
            store.setGoodsCount(dayStatics1.getGoodsCount());
            store.setArticleCount(dayStatics1.getArticleCount());
            store.setOrderCount(dayStatics1.getPayOrderCount());
            store.setPayAmount(dayStatics1.getPayAmount());
            if (dayStatics1.getPayOrderCount() > 0) {
                SysStore sysStore = storeMapper.selectById(dayStatics1.getStoreId());
                if (sysStore != null) {
                    SysStoreDepositLog entity = new SysStoreDepositLog();
                    if (sysStore.getAmount() == null || sysStore.getAmount().compareTo(BigDecimal.ZERO) == 0) {
                        entity.setBalance(dayStatics1.getPayAmount());
                        store.setAmount(dayStatics1.getPayAmount());
                    } else {
                        entity.setBalance(sysStore.getAmount().add(dayStatics1.getPayAmount()));
                        store.setAmount(sysStore.getAmount().add(dayStatics1.getPayAmount()));
                    }
                    entity.setCredit(dayStatics1.getPayAmount());
                    entity.setStoreId(dayStatics1.getStoreId());
                    entity.setCreateTime(new Date());
                    entity.setUpdateTime(new Date());
                    entity.setType(6);
                    sysStoreDepositLogMapper.insert(entity);
                }

            }
            storeMapper.updateById(store);
        }
        log.info("商户统计end====：{}", DateUtils.getNowDate());
        return ReturnT.SUCCESS;
    }
    /**
     * 每周一 生成上周的结算报告
     *
     * @throws InterruptedException
     */
    @XxlJob("genStoreSettleRecords")
    public ReturnT<String> genStoreSettleRecords(String param) throws InterruptedException {

        List<AdminDayStatics> dayStaticss = dayStaticsMapper.selectLastWeekAdminDayStaticsGroupBySId();
        log.info("生成上周的结算报告 商户统计：{}，共{}个商户需要需要同步", DateUtils.getNowDate(), dayStaticss.size());
        for (AdminDayStatics dayStatics : dayStaticss) {
            SysStoreSettleRecords records = new SysStoreSettleRecords();
            records.setCreateTime(new Date());
            records.setPayAmount(dayStatics.getPayAmount());
            records.setStatus(0);
            records.setStoreId(dayStatics.getStoreId());
            records.setStoreName(dayStatics.getStoreName());
            storeSettleRecordsMapper.insert(records);
        }
        return ReturnT.SUCCESS;
    }

    /**
     * 将拆单订单 更新为已完成 或者 部分退款
     *
     * @throws InterruptedException
     */
    @XxlJob("parentOrderStatus")
    public ReturnT<String> parentOrderStatus(String param) throws InterruptedException {
        List<Integer> ids = Arrays.asList(OrderStatus.TRADE_SUCCESS.getValue(), OrderStatus.PART_REFUND.getValue());

        List<OmsOrder> page = orderMapper.selectList(new QueryWrapper<OmsOrder>().notIn("status", ids).isNull("store_id").select(ConstansValue.sampleOrderList));
        log.info("将拆单订单 更新为已完成 或者 部分退款：{}，共{}", DateUtils.getNowDate(), page.size());
        for (OmsOrder omsOrder : page) {
            List<OmsOrder> itemList = orderMapper.selectList(new QueryWrapper<OmsOrder>().eq("pid", omsOrder.getId()));
            Boolean flag = true;
            Boolean part_refund = false;
            for (OmsOrder order : itemList) {
                if (order.getStatus() != OrderStatus.TRADE_SUCCESS.getValue()) {
                    flag = false;
                }
                if (order.getStatus() == OrderStatus.REFUND.getValue()) {
                    part_refund = true;
                }
            }
            // 部分退款
            if (part_refund) {
                omsOrder.setStatus(OrderStatus.PART_REFUND.getValue());
                orderMapper.updateById(omsOrder);
            }
            // 完全成交
            if (flag) {
                omsOrder.setStatus(OrderStatus.TRADE_SUCCESS.getValue());
                orderMapper.updateById(omsOrder);
            }
        }
        return ReturnT.SUCCESS;
    }
}
